package com.example.springboottest.p6spy;

import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import org.springframework.util.StringUtils;

/**
 * 自定义sql格式化输出
 */
public class FinalSqlFormat implements MessageFormattingStrategy {
    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String
            prepared, String sql, String url) {
        String result = "";

        // 单行sql
        if (sql != null) {
            if (StringUtils.isEmpty(sql))
                sql = prepared;

            result = sql //
                    .replaceAll("\\n", "") //
                    .replaceAll("\\s+", " ");
        }

        //非sql语句, 打印category
        if (category != null && !category.equals(Category.STATEMENT.getName())) {
            result = "[" + category + "]";
        }

        String currentSchema = SchemaRecordEventListener.currentSchema.get();
        return String.format("#%d|%5s|%4d| %s", connectionId, currentSchema, elapsed, result);
    }
}